package com.ruoyi.web.controller.module.estate;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.excel.IntegralRecordExcel;
import com.ruoyi.system.domain.module.excel.ProductOrderExcel;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.property.PropertyFeeOrder;
import com.ruoyi.system.domain.module.setMeal.SetMealOrder;
import com.ruoyi.system.domain.module.splitAccount.SplitAccount;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.product.IProductOrderService;
import com.ruoyi.system.service.module.property.IPropertyFeeOrderService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.setMeal.ISetMealOrderService;
import com.ruoyi.system.service.module.splitAccount.ISplitAccountService;
import com.ruoyi.system.service.module.wx.IUserIntegralRecordService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 小区列Controller
 *
 * @author ruoyi
 * @date 2021-08-18
 */
@Validated
@Api(value = "小区列控制器", tags = {"小区列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/estate")
public class EstateController extends BaseController {

	private final IEstateService estateService;
	private final IPropertyService propertyService;
	private final ISplitAccountService splitAccountService;
	private final IProductOrderService productOrderService;
	private final IPropertyFeeOrderService propertyFeeOrderService;
	private final ISetMealOrderService setMealOrderService;
	private final IUserIntegralRecordService userIntegralRecordService;


	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

    /**
     * 查询小区列列表
     */
    @ApiOperation("查询小区列列表")
    @PreAuthorize("@ss.hasPermi('module:estate:list')")
    @GetMapping("/list")
    public TableDataInfo<Estate> list(@Validated Estate estate) {
    	SysUser sysUser = getUser();
        QueryWrapper<Estate> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(estate.getEstateName())){
            qw.like("estate_name",estate.getEstateName());
        }
        //用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员   4 - 商家用户
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("id",sysUser.getEstateId());
		}else{
			if(estate.getPropertyId() != null){
				qw.eq("property_id",estate.getPropertyId());
			}
		}
		TableDataInfo<Estate> td = PageUtils.buildDataInfo(estateService.page(PageUtils.buildPage(),qw));
        List<Estate> list = td.getRows();
        list.forEach(estate1 -> {
			Property property = propertyService.getById(estate1.getPropertyId());
			if(property != null){
				estate1.setPropertyName(property.getPropertyName());
			}
			if(StrUtil.isNotEmpty(estate1.getQrCode())){
				estate1.setQrCode(imgUrl + estate1.getQrCode());
			}
		});
        return td;
    }

	/**
	 * 查询小区列列表
	 */
	@ApiOperation("查询小区列列表")
//	@PreAuthorize("@ss.hasPermi('module:estate:list')")
	@GetMapping("/statistics")
	public TableDataInfo<Estate> statistics(@Validated Estate estate) {
		SysUser sysUser = getUser();
		QueryWrapper<Estate> qw = new QueryWrapper<>();
		if(StrUtil.isNotEmpty(estate.getEstateName())){
			qw.eq("estate_name",estate.getEstateName());
		}
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员   4 - 商家用户
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			qw.eq("id",sysUser.getEstateId());
		}else{
			if(estate.getPropertyId() != null){
				qw.eq("property_id",estate.getPropertyId());
			}

			if(estate.getId() != null){
				qw.eq("id",estate.getId());
			}
		}

		TableDataInfo<Estate> td = PageUtils.buildDataInfo(estateService.page(PageUtils.buildPage(),qw));
		List<Estate> list = td.getRows();
		list.forEach(estate1 -> {
			Property property = propertyService.getById(estate1.getPropertyId());
			if(property != null){
				estate1.setPropertyName(property.getPropertyName());
			}
			if(StrUtil.isNotEmpty(estate1.getQrCode())){
				estate1.setQrCode(imgUrl + estate1.getQrCode());
			}

			Map<String,Object> map = new HashMap<>();
			map.put("estate_id",estate1.getId());
			map.put("order_type", 0);

			if(StrUtil.isNotEmpty(estate.getBeginDate())){
				map.put("begin_time",estate.getBeginDate() + " 00:00:00");
				map.put("end_time",estate.getEndDate() + " 23:59:59");
			}
			if(estate.getPayType() !=null){
				map.put("pay_type", estate.getPayType() );
			}

			ProductOrderExcel productOrderExcel = productOrderService.selectTongjiByEstateId(map);
			estate1.setProductOrderExcel(productOrderExcel);


			Map<String,Object> mapDevice = new HashMap<>();
			mapDevice.put("estate_id",estate1.getId());
			mapDevice.put("order_type", 1);
			if(StrUtil.isNotEmpty(estate.getBeginDate())){
				mapDevice.put("begin_time",estate.getBeginDate() + " 00:00:00");
				mapDevice.put("end_time",estate.getEndDate() + " 23:59:59");
			}
			if(estate.getPayType() !=null){
				mapDevice.put("pay_type", estate.getPayType() );
			}
			ProductOrderExcel deviceOrderExcel = productOrderService.selectTongjiByEstateId(mapDevice);
			estate1.setDeviceOrderExcel(deviceOrderExcel);


			Map<String,Object> mapProperty = new HashMap<>();
			mapProperty.put("estate_id",estate1.getId());
			if(StrUtil.isNotEmpty(estate.getBeginDate())){
				mapProperty.put("begin_time",estate.getBeginDate() + " 00:00:00");
				mapProperty.put("end_time",estate.getEndDate() + " 23:59:59");
			}
			if(estate.getPayType() !=null){
				mapProperty.put("pay_platform", estate.getPayType() );
			}
			PropertyFeeOrder propertyFeeOrder = propertyFeeOrderService.selectOrderTongjiByEstateId(mapProperty);
			estate1.setPropertyFeeOrder(propertyFeeOrder);


			Map<String,Object> mapSetMeal = new HashMap<>();
			mapSetMeal.put("estate_id",estate1.getId());
			if(StrUtil.isNotEmpty(estate.getBeginDate())){
				mapSetMeal.put("begin_time",estate.getBeginDate() + " 00:00:00");
				mapSetMeal.put("end_time",estate.getEndDate() + " 23:59:59");
			}
			if(estate.getPayType() !=null){
				mapSetMeal.put("pay_type", estate.getPayType() );
			}
			SetMealOrder setMealOrder = setMealOrderService.selectOrderTongjiByEstateId(mapSetMeal);
			estate1.setSetMealOrder(setMealOrder);


			Map<String,Object> mapIntegral = new HashMap<>();
			mapIntegral.put("estate_id",estate1.getId());
			if(StrUtil.isNotEmpty(estate.getBeginDate())){
				mapIntegral.put("begin_time",estate.getBeginDate() + " 00:00:00");
				mapIntegral.put("end_time",estate.getEndDate() + " 23:59:59");
			}
			IntegralRecordExcel integralRecordExcel = userIntegralRecordService.selectTongjiByEstateId(mapIntegral);
			estate1.setIntegralRecord(integralRecordExcel);

		});
		return td;
	}

	/**
	 * 查询小区列列表
	 */
	@ApiOperation("查询小区列列表")
	@PreAuthorize("@ss.hasPermi('module:estate:list')")
	@GetMapping("/listAll")
	public AjaxResult listAll(@Validated Estate estate) {
		SysUser sysUser = getUser();
		QueryWrapper<Estate> qw = new QueryWrapper<>();
		qw.eq("state",0);
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				qw.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				qw.eq("id",sysUser.getEstateId());
			}  else{
				if(estate.getPropertyId()!=null){
					qw.eq("property_id",estate.getPropertyId());
				}
			}
		}
		List<Estate> list = estateService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (Estate estate1 : list){
				Property property = propertyService.findById(estate1.getPropertyId());
				if(property!=null){
					estate1.setPropertyName(property.getPropertyName());
				}
			}
		}
		return AjaxResult.success(list);
	}


	/**
     * 获取小区列详细信息
     */
    @ApiOperation("获取小区列详细信息")
    @PreAuthorize("@ss.hasPermi('module:estate:query')")
    @GetMapping("/{id}")
    public AjaxResult<Estate> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Estate estate = estateService.getById(id);
		SysUser sysUser = getUser();
        if(estate!=null){
			estate.setIsCanEdit(1);
        	String[] areas = { estate.getProv(),estate.getCity(),estate.getDistrict() };
			estate.setProvinceArray(areas);
			if(sysUser!=null){
				if(sysUser.getUserType() == 3){//小区
					estate.setIsCanEdit(0);
				}
			}
		}
        return AjaxResult.success(estate);
    }

    /**
     * 新增小区列
     */
    @ApiOperation("新增小区列")
    @PreAuthorize("@ss.hasPermi('module:estate:add')")
    @Log(title = "小区列", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody Estate estate) {
    	boolean bl = estateService.save(estate);
		if(bl){
			try{
//				String qrcode = "";
//				String fileName = "estate_qr_" + estate.getId() + ".jpg";
//				String content = "{\"qrtype\":\"estate\",\"id\":\""+estate.getId()+"\"}";
//				Aes aes = new Aes();
//				int upload_type = FileUploadUtils.TYPE_ESTATE_PHOTOS;
//				content = aes.encrypt(content);
//				System.out.println("content:  "+ content);
//				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;

				String qrCode = "";
				String fileName = "device_qr_" + estate.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/estate/info?id=" + estate.getId();
				int upload_type = FileUploadUtils.TYPE_ESTATE_PHOTOS;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, estate.getEstateName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
				estate.setQrCode(img_key);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			bl = estateService.updateById(estate);
			if(bl){
				QueryWrapper<SplitAccount> qw = new QueryWrapper<>();
				qw.eq("account_type",2);
				qw.eq("account_id",estate.getId());
				qw.last("limit  1");
				SplitAccount splitAccount = splitAccountService.getOne(qw);
				if(splitAccount == null){
					splitAccount = new SplitAccount();
					splitAccount.setAccountType(2);
					splitAccount.setAccountId(estate.getId());
					splitAccount.setSplitMoney(new BigDecimal(0));
					splitAccount.setFreezen(new BigDecimal(0));
					splitAccountService.save(splitAccount);
				}
			}
		}
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 修改小区列
     */
    @ApiOperation("修改小区列")
    @PreAuthorize("@ss.hasPermi('module:estate:edit')")
    @Log(title = "小区列", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody Estate estate) {
    	boolean bl = estateService.updateById(estate);
    	if(bl){
			QueryWrapper<SplitAccount> qw = new QueryWrapper<>();
			qw.eq("account_type",2);
			qw.eq("account_id",estate.getId());
			qw.last("limit  1");
			SplitAccount splitAccount = splitAccountService.getOne(qw);
			if(splitAccount == null){
				splitAccount = new SplitAccount();
				splitAccount.setAccountType(2);
				splitAccount.setAccountId(estate.getId());
				splitAccount.setSplitMoney(new BigDecimal(0));
				splitAccount.setFreezen(new BigDecimal(0));
				splitAccountService.save(splitAccount);
			}
		}

        return toAjax(bl ? 1 : 0);
    }

    /**
     * 删除小区列
     */
    @ApiOperation("删除小区列")
    @PreAuthorize("@ss.hasPermi('module:estate:remove')")
    @Log(title = "小区列" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(estateService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:estate:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody Estate estate) {
		if(estate.getId()!=null){
			try{
				estate = estateService.getById(estate.getId());
//				String qrcode = "";
//				String fileName = "estate_qr_" + estate.getId() + ".jpg";
//				String content = "{\"qrtype\":\"estate\",\"id\":\""+estate.getId()+"\"}";
//				Aes aes = new Aes();
//				int upload_type = FileUploadUtils.TYPE_ESTATE_PHOTOS;
//				content = aes.encrypt(content);
//				System.out.println("content:  "+ content);
//				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;


				String qrCode = "";
				String fileName = "device_qr_" + estate.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/noticeGroup/?eId=" + estate.getId();
				int upload_type = FileUploadUtils.TYPE_ESTATE_PHOTOS;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;

				QRCodeUtilEx.createQrCodeImg(content, estate.getEstateName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
				qrCode = img_key;
				estate.setQrCode(qrCode);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (estateService.updateById(estate)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}

	public String estateName(Integer id){
		QueryWrapper<Estate> qw = new QueryWrapper<>();
		qw.eq("id",id);
		List<Estate> list=estateService.list(qw);
		String estateName=null;
		for(Estate est:list){
			estateName=est.getEstateName();
		}
		return  estateName;
	}







}
